<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-12-05
 * Time: 15:57
 */

class test_controller extends general_controller{
    public function __construct(){
        parent::__construct();
        $this->_weixin = array(
            'appid' =>'wx06ba160628f3511c',
            'secret'=>'4ef6a15324d708e4b4b4f6092963773a',
            'mchid' => '1517652191',
            'key' => '8eda5401d6c19413ddb0cddea33f0319',
            'notify_url'=>'https://gift.kuajiewl.com/wapi/wxpay_notify.html',
            'vip_notify_url'=>'https://gift.kuajiewl.com/wapi/wxpay_notify_vip.html',
            'postage_notify_url'=>'https://gift.kuajiewl.com/wapi/wxpay_notify_postage.html',
            'income_type' => ['直推奖','分享奖','服务奖','分享产品返利（一级返利）'],
            'prize' => ['金卡VIP直推补贴','金卡VIP收藏','金卡VIP服务补贴','尊贵VIP收藏补贴','尊贵VIP直推补贴','尊贵VIP服务补贴'],
        );
        $this->_wx_template = 'hDuWaRojW0-5vKgDMenMjmGv-0SmqDTioJln9PNUEXY';
        $this->_key_user = 'user_';
        $this->_key_user_cart = 'cart_';
        $this->_cache_year = 31536000;
        $this->_postage_price = 0.01;
        $this->_order_status = array('交易取消','等待付款','等待发货','等待签收','交易完成');
        $this->_vip_price = ['vip1' => 0.01, 'vip2' => 0.01];
    }

    public function action_wxpay_notify(){

        $wechat_arr = array(
            'user_id' => 4,
            'openid' => 'owpeA4o25ej8WUJmTW4Qzha-mUl0',
            //'out_trade_no' => 606424004241334, //vip2
            'out_trade_no' => 614132002901390, //vip1
        );


        $data = array();
        $result = $this->orderhandle($wechat_arr);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {


            //删除购物车中的商品
            $order_goods_model = new order_goods_model();
            $order_goods = $order_goods_model->find_all(array('order_id' => $wechat_arr['out_trade_no']));

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            //微信支付更新销量
            $order_goods = $order_goods_model->find_all(array('order_id' => $wechat_arr['out_trade_no']), null, 'goods_id');
            $in_id = '';
            foreach($order_goods as $g){
                $in_id .= $g['goods_id'] . ',';
            }
            $in = substr($in_id, 0, -1);
            $goods_mode = new goods_model();
            $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods SET sell=sell+1 WHERE goods_id IN ($in)";
            $goods_mode->query($sql);

            //自动打印订单
            //商品列表
            $condition = array('order_id' => $wechat_arr['out_trade_no']);

            $order_model = new order_model();
            $order = $order_model->find($condition);

            //返佣,不是本人，且非0,邀请者是VIP
            $user_nodel = new user_model();
            $user_acctount = new user_account_model();
            $acctount_log = new user_account_log_model();

            $sql = "SELECT invite,vip FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$order['user_id']}'";

            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($sql, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            $user_data = $user_nodel->query($sql);
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($user_data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


            if($user_data[0]['vip'] > 0 && $user_data[0]['invite'] > 0){
                $sql = "SELECT user_id,invite,vip,md FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$user_data[0]['invite']}'";
                $invite_user_data = $user_nodel->query($sql);
                $invite_user = $invite_user_data[0];
                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($invite_user, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

                if($invite_user['user_id'] != $order['user_id'] && $invite_user['vip'] > 0){


                    //更新账户，更新收入日志
                    echo $sql = "SELECT rake_back FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}goods WHERE goods_id='{$in}'";
                    $rake_data = $goods_mode->query($sql);
                    $rake = $rake_data[0];var_dump($rake);
                    $rake_back = $rake['rake_back'];

                   echo $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$rake_back,today=today+$rake_back WHERE user_id='{$user_data[0]['invite']}';";
                    $ret = $user_acctount->execute($sql);


                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($invite_user['vip'] == 1){
                            $prize = 0;
                        }
                        if($invite_user['vip'] == 2){
                            $prize = 3;
                        }
                        $time = time();
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data[0]['invite']}', '{$prize}', '{$rake_back}','1', '0', '{$time}');";
                        $acctount_log->execute($sql);
                    }

                }


                //如果是市场总监增加10%收益
                if($invite_user['md'] == 1){
                    $sql = "SELECT king,zun FROM {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user WHERE user_id='{$order['user_id']}'";
                    $order_user = $user_nodel->query($sql);

                    $setting_model = new setting_model();
                    $rs = $setting_model->get_config();

                    $vip_settings = json_decode($rs['vip_settings'], true);
                    if($order_user['king'] == 1){
                        $mdback = $vip_settings['king_service_back'] * 0.1;
                    }
                    if($order_user['zun'] == 1){
                        $mdback = $vip_settings['zun_service_back'] * 0.1;
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$mdback,today=today+$mdback WHERE user_id='{$user_data[0]['invite']}';";
                    $ret = $user_acctount->execute($sql);
                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($invite_user['vip'] == 1){
                            $prize = 8;
                        }
                        if($invite_user['vip'] == 2){
                            $prize = 9;
                        }
                        $time = time();
                        if($order['invite'] > 0){
                            $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$order['invite']}', '{$prize}', '{$mdback}','1', '2', '{$time}');";
                            $acctount_log->execute($sql);
                        }

                    }
                }
            }



            $goods_list = $order_goods_model->get_goods_list($ret['out_trade_no']);
            //发货列表
            $shipping_model = new order_shipping_model();
            $shipped_list = $shipping_model->find_all($condition, 'dateline DESC');
            if(!empty($shipped_list)) {
                foreach($shipped_list as &$v) $v['carrier'] = $this->carrier_list[$v['carrier_id']]['name'];
            }


            //$shipped_list = $shipped_list;
            //日志列表
            $log_model = new order_log_model();
            if($log_list = $log_model->find_all($condition, 'dateline DESC')) {
                $this->operate_map = $log_model->operate_map;
            }
            $name = '';
            foreach($goods_list as $v){
                $name .= $v['goods_name'] . ' ';
            }





            //发送模板消息
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['order_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => $name),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/dingdan?currentTab=3&otype=sign';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息

            /**$setting_model = new setting_model();
            $rs = $setting_model->get_config();
            if($rs['printer'][0] == '' || $rs['printer'][1] == ''){
            jsonEcho(array('ret' => 22, 'msg'=>'请先设置打印机'));
            }
            $result = sendSelfFormatOrderInfo(1, $content, $rs['printer'][0], $rs['printer'][1]);
            $ret = json_decode($result, true);
            if(in_array($ret['responseCode'], array(0,1,2,3))){

            }else{
            file_put_contents($file, var_export($ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            }**/

        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            echo 'fail';
        }
    }
    //***************************
    //  订单处理 接口
    //***************************
    public function orderhandle($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $out_trade_no = trim($data['out_trade_no']);
        $order_model = new order_model();
        $condition = array('order_id' => $out_trade_no, 'order_status' => 1);
        $order_info = $order_model->find($condition);

        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $order_model->update($condition, array('order_status' => 2, 'payment_date' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {
            file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export(666, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }

    public function action_wxpay_notify_vip(){

        $path = $_SERVER['DOCUMENT_ROOT'] . "/logs/";
        $file = $path . "wechat_mon_".date("Yn").".txt";

        $wechat_arr = array(
            'user_id' => 4,
            'openid' => 'owpeA4o25ej8WUJmTW4Qzha-mUl0',
            //'out_trade_no' => 606424004241334, //vip2
            'out_trade_no' => 606424004241335, //vip1
        );
        $result = $this->orderhandle_vip($wechat_arr);
        //file_put_contents($file, var_export($result) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
        if ($result['ret'] == 0) {

            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo 'SUCCESS';

            $condition = array('order_id' => $wechat_arr['out_trade_no']);

            $order_vip_model = new order_vip_model();
            $order = $order_vip_model->find($condition);
            $vip = 0;
            $setting_model = new setting_model();
            $rs = $setting_model->get_config();

            $vip_settings = json_decode($rs['vip_settings'], true);
            if($order['vip'] == 'vip1'){
                $vip = 1;
                $vip_back = $vip_settings['king_zhitui'];
                $vip_back2 = $vip_settings['king_zhitui2'];
            }elseif($order['vip'] == 'vip2'){
                $vip = 2;
                $vip_back = $vip_settings['zun_zhitui'];
                $vip_back2 = $vip_settings['zun_zhitui2'];
            }

            $user_model = new user_model();
            $affected = $user_model->update(array('user_id' => $wechat_arr['user_id']), array('vip' => $vip));
            if($affected) {
                file_put_contents($file, var_export('更新用户vip成功', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            } else {
                file_put_contents($file, var_export('更新用户vip失败', true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            }

            //========邀请人加收益start=======
            //更新账户，更新收入日志

            //一级
            $time = time();
            $user_acctount = new user_account_model();
            $acctount_log = new user_account_log_model();
            $user_data = $user_model->find(['user_id' => $wechat_arr['user_id']]);

            $invite_user_data = $user_model->find(['user_id' => $user_data['invite']]);
            if($invite_user_data['vip'] > 0){
                if($user_data['invite'] > 0 && $user_data['invite'] != $user_data['user_id']){

                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back,today=today+$vip_back WHERE user_id='{$user_data['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($vip == 1){
                            $prize = 0;
                        }
                        if($vip == 2){
                            $prize = 4;
                        }
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data['invite']}', '{$prize}', '{$vip_back}','1', '0', '{$time}');";
                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }


                //二级
                $user_data2 = $user_model->find(['user_id' => $user_data['invite']]);
                if($user_data2['invite'] > 0 && $user_data2['vip'] > 0){

                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$vip_back2,today=today+$vip_back2 WHERE user_id='{$user_data2['invite']}';";

                    file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                    $ret = $user_acctount->execute($sql);

                    //插入日志
                    if($ret){
                        $prize = 100;
                        if($vip == 1){
                            $prize = 0;
                        }
                        if($vip == 2){
                            $prize = 4;
                        }
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data2['invite']}', '{$prize}', '{$vip_back2}','1', '0', '{$time}');";

                        file_put_contents($file, var_export($sql, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
                        $acctount_log->execute($sql);
                    }
                }


                //尊贵VIP会员直推20个尊贵VIP会员升级为市场总监，在团队伞下每新增一个尊贵VIP奖励20元，每新增一个金卡VIP奖励2元
                $count = $user_model->find_count(['invite' => $user_data['invite']]);
                if($count >= 20){
                    //不是市场总监则更新
                    $user_data3 = $user_model->find(['user_id' => $user_data['invite']]);
                    if($user_data3['md'] == 0){
                        $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user SET md='1' WHERE user_id='{$user_data3['user_id']}';";
                        $user_model->execute($sql);
                    }
                    if($vip == 1){
                        $addmoney = $vip_settings['king_md'];
                        $prize = 6;
                    }
                    if($vip == 1){
                        $addmoney = $vip_settings['zun_md'];
                        $prize = 7;
                    }
                    $sql = "UPDATE {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account SET balance=balance+$addmoney,today=today+$addmoney WHERE user_id='{$user_data3['user_id']}';";
                    $ret = $user_acctount->execute($sql);
                    //插入日志
                    if($ret){
                        $sql = "INSERT INTO {$GLOBALS['mysql']['MYSQL_DB_TABLE_PRE']}user_account_log (`user_id`,`prize`, `balance`, `num`,`type`, `dateline`)
                     VALUES ('{$user_data3['user_id']}', '{$prize}', '{$addmoney}','1', '2', '{$time}');";
                        $acctount_log->execute($sql);
                    }
                }
            }

            //========邀请人加收益end=======


            //发送模板消息
            //$tid = 'hDuWaRojW0-5vKgDMenMjmGv-0SmqDTioJln9PNUEXY';
            $prepay_id = $this->memcache_get('prepay_id' . $wechat_arr['openid']);
            /**$data = [
            'keyword1' => array('value' =>  $ret['out_trade_no']),
            'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
            'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
            'keyword4' => array('value' => '购买vip' . $order['vip']),
            'keyword5' => array('value' => date('Y-m-d H:i:s')),
            'keyword6' => array('value' => '微信支付'),
            'keyword7' => array('value' => '购买vip服务'),
            'keyword8' => array('value' => ''),
            ];**/
            $data = [
                'keyword1' => array('value' =>  $ret['out_trade_no']),
                'keyword2' => array('value' =>  $order['goods_amount'] . '元'),
                'keyword3' => array('value' => date('Y-m-d H:i:s', $order['created_date'])),
                'keyword4' => array('value' => '购买vip' . $order['vip']),
                'keyword5' => array('value' => date('Y-m-d H:i:s')),
                'keyword6' => array('value' => '微信支付'),
            ];
            $page = 'pages/user/user';
            $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);
            if($send_ret['errcode'] != 0){
                //token过期重试一次
                $this->memecache_delete('access_token');
                $send_ret = $this->sendTemplate($wechat_arr['openid'],$this->_wx_template, $prepay_id, $page, $data);
            }
            //发送模板消息
            file_put_contents($file, var_export($send_ret, true) . __LINE__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);


        }else{
            $contents = 'error => '.json_encode($result, JSON_UNESCAPED_UNICODE);  // 写入的内容
            //$files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($file, $contents . __LINE__, FILE_APPEND | LOCK_EX);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
    public function memecache_set($key, $value, $time=600){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->expire($key, $time);
        $redis->set($key,$value);
    }

    public function memcache_get($key){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis->get($key);
    }
    public function memecache_delete($key){
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        return $redis->delete($key);
    }
    public function sendTemplate($touser, $tid, $prepay_id, $page, $arr){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $this->get_acess_token();
        $data = array(
            'touser' => $touser,
            'template_id' => $tid,
            'page' => $page,
            "form_id" => $prepay_id,
            'data' => $arr
        );
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        return $this->http_request($url, $json);
    }
    //获取access token
    public function get_acess_token($update=0){
        $key = 'access_token';
        if($update == 0){
            if($token = $this->memcache_get($key)){
                if(is_string($token)){
                    return $token;
                }
            }
        }

        $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_weixin['appid']}&secret={$this->_weixin['secret']}";

        $token = $this->http_request($url);
        if(isset($token['access_token'])){
            $this->memecache_set($key, $token['access_token'], 7000);
            return $token['access_token'];
        }else{
            $this->memecache_delete($key);
        }

    }
    //curl request
    public function http_request($url, $data=array()){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);#以文件流形式返回
        if($data){
            curl_setopt($ch, CURLOPT_POST, 1); #post方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        $ret = json_decode($output, true);
        if(is_array($ret)){
            $arr = $ret;
        }else{
            $arr = $output;
        }
        //释放curl句柄
        curl_close($ch);
        return $arr;
    }

    public function orderhandle_vip($data){
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($data, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        $out_trade_no = trim($data['out_trade_no']);
        $order_vip_model = new order_vip_model();
        $condition = array('order_id' => $out_trade_no, 'order_status' => 1);
        $order_info = $order_vip_model->find($condition);
        var_dump($condition);
var_dump($order_vip_model->dump_sql());
        if (!$order_info) {
            return array('ret' => 2,'err'=>'没有找到支付订单！');
        }
        $res = $order_vip_model->update($condition, array('order_status' => 2, 'payment_date' => time()));
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/logs/wechat_mon_' . date('Yn') . '.txt', var_export($res, true) . __LINE__ . __FUNCTION__ . "\r\n\r\n", FILE_APPEND | LOCK_EX);

        if ($res) {

            return array('ret' => 0,'data' => $order_info);
        }else{
            return array('ret' => 2,'msg' => '订单不存在');
        }
    }
}